package cn.com.utt.unms.controller;

import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson.JSONObject;
import cn.com.utt.common.exception.BusinessException;
import cn.com.utt.common.service.UserService;
import cn.com.utt.common.util.DateUtil;
import cn.com.utt.common.util.SignUtils;
import cn.com.utt.common.vo.RestResult;
import cn.com.utt.common.vo.User;
import cn.com.utt.unms.pojo.Device;
import cn.com.utt.unms.pojo.UserRecord;
import cn.com.utt.unms.pojo.WxCode;
import cn.com.utt.unms.service.DeviceService;
import cn.com.utt.unms.service.JsonService;
import cn.com.utt.unms.service.UserRecordService;
import cn.com.utt.unms.vo.AuthResult;
import cn.com.utt.unms.vo.UnExpiredRecord;

//@RestController
//@RequestMapping("v1/json")
public class JsonController {

//	@Autowired
//	private JsonService jsonService;
//
//	@Autowired
//	private DeviceService deviceService;
//
//	@Autowired
//	private UserService userService;
//
//	@Autowired
//	private UserRecordService userRecordService;
//
//	private static String SECRET = "1623`@wifi";
//
//	@RequestMapping(value = "/checkPhoneIsRegin", method = { RequestMethod.POST })
//	public Map<String, Object> checkPhoneIsRegin(HttpServletRequest request, HttpServletResponse response) {
//		RestResult result = new RestResult();
////
////		String deviceId = request.getParameter("deviceId");
////
////		String phone = request.getParameter("phone");
////		String mac = request.getParameter("mac");
////
////		Device device = deviceService.queryDeviceBySn(deviceId);
////
////		User user = userService.queryById(device.getUserId());
////
////		response.addHeader("content-type", "text/html");
////		response.setCharacterEncoding("utf-8");
////
////		// PrintWriter out = null;
////		try {
////			// out = response.getWriter();
////			if (null == phone || phone.length() == 0) {
////				// out.print("{\"state\":\"3\",\"message\":\"手机号不能为空\"}");
////				result.setErrorCode(3);
////				result.setErrorMsg("手机号不能为空!");
////			} else {
////				try {
////					int state = jsonService.checkPhoneIsRegin(phone.trim(), user.getCfgId(), mac.trim());
////					result.setErrorCode(state);
////					// out.print("{\"state\":\"" + state +
////					// "\",\"message\":\"\"}");
////
////				} catch (BusinessException e) {
////					// out.print("{\"state\":\"3\",\"message\":\"error\"}");
////					result.setErrorCode(3);
////					result.setErrorMsg("error");
////				}
////			}
////			// out.flush();
////		} catch (Exception e) {
////			e.printStackTrace();
////			result.setErrorCode(1);
////			result.setErrorMsg("异常");
////		}
//		return result.toJsonObject();
//	}
//
//	@RequestMapping(value = "/phoneRegin", method = { RequestMethod.POST })
//	public Map<String, Object> phoneRegin(HttpServletRequest request, HttpServletResponse response) {
//		RestResult result = new RestResult();
//		String deviceId = request.getParameter("deviceId");
//		String phone = request.getParameter("phone");
//		HttpSession session = request.getSession();
//		Device device = deviceService.queryDeviceBySn(deviceId);
//		User user = userService.queryById(device.getId());
//
//		response.addHeader("content-type", "text/html");
//		response.setCharacterEncoding("utf-8");
//		// PrintWriter out = null;
//		try {
//			// out = response.getWriter();
//			if (null == phone || phone.length() == 0) {
//				// out.print("{\"state\":\"2\",\"message\":\"手机号不能为空!\"}");
//				result.setErrorCode(1);
//				result.setErrorMsg("手机号不能为空!");
//			} else {
//				try {
//					int state = jsonService.phoneRegin(phone, user.getId(), session);
//					if (state == 1) {
//						// out.print("{\"state\":\"1\",\"message\":\"\"}");
//						result.setErrorCode(0);
//						result.setErrorMsg("注册成功！");
//					} else if (state == 2) {
//						// out.print("{\"state\":\"2\",\"message\":\"密码发送失败!\"}");
//						result.setErrorCode(1);
//						result.setErrorMsg("密码发送失败！");
//					} else if (state == 4) {
//						// 已注册过
//						// out.print("{\"state\":\"2\",\"message\":\"手机号已注册!\"}");
//						result.setErrorCode(1);
//						result.setErrorMsg("手机号已注册!");
//					} else {
//						// 余额不足
//						// out.print("{\"state\":\"2\",\"message\":\"获取密码失败!\"}");
//						result.setErrorCode(1);
//						result.setErrorMsg("获取密码失败!");
//					}
//				} catch (BusinessException e) {
//					// out.print("{\"state\":\"2\",\"message\":\"注册失败!\"}");
//					result.setErrorCode(1);
//					result.setErrorMsg("注册失败!");
//				}
//			}
//			// out.flush();
//		} catch (Exception e) {
//			e.printStackTrace();
//			result.setErrorCode(1);
//			result.setErrorMsg("注册失败!");
//		} finally {
//			// if (out != null) {
//			// out.close();
//			// }
//		}
//		return result.toJsonObject();
//	}
//
//	@RequestMapping(value = "/checkWxIsRegin", method = { RequestMethod.POST })
//	public Map<String, Object> checkWxIsRegin(HttpServletRequest request, HttpServletResponse response) {
//		RestResult result = new RestResult();
//
//		String deviceId = request.getParameter("deviceId");
//		String mac = request.getParameter("mac");
//
//		response.addHeader("content-type", "text/html");
//		response.setCharacterEncoding("utf-8");
//
//		PrintWriter out = null;
//		try {
//			out = response.getWriter();
//
//			if (null == deviceId || deviceId.length() == 0 || mac == null || mac.length() == 0) {
//				out.print("{\"state\":\"3\",\"message\":\"参数不能为空\"}");
//				result.setErrorCode(1);
//				result.setErrorMsg("参数不能为空！");
//			} else {
//				// 查看wx_code表cfg_id与mac对应记录是否存在
//				WxCode wxCode = jsonService.checkWxIsRegin(deviceId, mac);
//				if (wxCode == null) {
//					out.print("{\"state\":\"0\",\"message\":\"\"}");
//					// result.setErrorCode(1);
//					// result.setErrorMsg("密码发送失败！");
//				} else {
//					out.print("{\"state\":\"1\",\"message\":\"\"}");
//					result.setErrorCode(1);
//					result.setErrorMsg("出错！");
//				}
//			}
//
//			out.flush();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (out != null) {
//				out.close();
//			}
//		}
//		return result.toJsonObject();
//	}
//
//	@RequestMapping(value = "/login", method = { RequestMethod.POST })
//	public Map<String, Object> login(Integer loginType, String sn, String ip, String mac, String sign, String username,
//			String password, String code, String phone, String gwAddress, String gwPort) {
////		RestResult result = new RestResult();
////		UserRecord record = new UserRecord();
////		Device device = deviceService.queryDeviceBySn(sn);
////		//User user = userService.queryById(device.getUserId());
////		User user = new User();
////		// 0:手机，1：手机免密码 ，2：微信，3：一键,6:帐号
////		int state = 0;
////		String error = "";
////		boolean flag = false;
////		int errorCode = 1;
////
////		try {
////			if (gwAddress == null || gwPort == null || sn == null || ip == null || mac == null
////					|| gwAddress.length() <= 0 || gwPort.length() <= 0 || sn.length() <= 0 || ip.length() <= 0
////					|| mac.length() <= 0) {
////				state = -1;
////				flag = false;
////				error = "参数错误";
////			} else {
////				record.setSn(sn);
////				record.setIp(ip);
////				record.setMac(mac);
////				record.setStartTime(new Timestamp(System.currentTimeMillis()));
////				record.setStatus((byte) 1);
////				String token = java.util.UUID.randomUUID().toString().replace("-", "");
////				record.setToken(token);
////
////				if (loginType == 0) {
////					if (phone == null) {
////						flag = false;
////						error = "手机号不能为空！";
////					} else if (password == null) {
////						flag = false;
////						error = "密码不能为空！";
////					} else {
////						record.setAuthType((byte) 0);
////						record.setUsername(phone);
////						state = jsonService.phoneLogin(user.getCfgId(), record, phone, password, mac);
////						if (state == 1) {
////							flag = true;
////							errorCode = 0;
////						} else if (state == 0) {
////							flag = false;
////							error = "帐号不存在或密码错误！";
////						} else if (state == 2) {
////							flag = false;
////							error = "您的认证次数超出限制！";
////						} else {
////							flag = false;
////							error = "您的帐号登录终端数超出限制！";
////						}
////					}
////				} else if (loginType == 1) {
////					// 已经注册过的用户，手机免密码登录
////					if (phone == null) {
////						flag = false;
////						error = "手机号不能为空！";
////					} else {
////						record.setAuthType((byte) 0);
////						record.setUsername(phone);
////						state = jsonService.phoneLogin(user.getCfgId(), record, phone, mac);
////						if (state == 1) {
////							flag = true;
////							errorCode = 0;
////						} else if (state == 0) {
////							flag = false;
////							error = "帐号不正确！";
////						} else if (state == 2) {
////							flag = false;
////							error = "您的认证次数超出限制！";
////						} else {
////							flag = false;
////							error = "您的帐号登录终端数超出限制！";
////						}
////
////					}
////				} else if (loginType == 2) {
////					// 微信登录
////					if (code == null) {
////						flag = false;
////						error = "上网密码不能为空！";
////					} else {
////						// 记录可能会有多条，此方法要修改
////						record.setAuthType((byte) 1);
////						state = jsonService.wxLogin(user.getCfgId(), record, code, mac);
////						if (state == 1) {
////							errorCode = 0;
////							flag = true;
////						} else if (state == 0) {
////							flag = false;
////							error = "密码不正确！";
////						} else if (state == 2) {
////							flag = false;
////							error = "您的认证次数超出限制！";
////						} else {
////							flag = false;
////							error = "您的帐号登录终端数超出限制！";
////						}
////					}
////				} else if (loginType == 3) {
////					// 一键登录
////					// 店铺是否支持一键登录，UTT默认不支持。
////					record.setAuthType((byte) 2);
////					record.setUsername(mac);
////					state = jsonService.onekeyLogin(user.getCfgId(), record, mac);
////					if (state == 1) {
////						flag = true;
////						errorCode = 0;
////					} else if (state == 0) {
////						flag = false;
////						error = "sorry,一键登录无法使用！";
////					} else if (state == 2) {
////						flag = false;
////						error = "您的认证次数超出限制！";
////					} else {
////						flag = false;
////						error = "您的帐号登录终端数超出限制！";
////					}
////				} else if (loginType == 6) {
////					// 账号认证
////					if (username == null || username.length() <= 0) {
////						flag = false;
////						error = "用户名不能为空！";
////					} else if (password == null || password.length() <= 0) {
////						flag = false;
////						error = "密码不能为空！";
////					} else {
////						record.setAuthType((byte) 4);
////						state = jsonService.accountLogin(user.getId(), record, username, password, mac);
////						if (state == 1) {
////							flag = true;
////							errorCode = 0;
////						} else if (state == 2) {
////							flag = false;
////							error = "您今日在本店认证次数已用完！";
////						} else {
////							flag = false;
////							error = "登录失败，建议尝试其它方式！";
////						}
////					}
////				}
////			}
////		} catch (BusinessException e) {
////			flag = false;
////			errorCode = 1;
////			error = "异常";
////		}
////
////		if (flag) {
////			// 如果是微信登录获取openid作为用户名
////			// 如果是快速登录，通过vtoken获取用户名
////			try {
////				if ((sign != null && !"".equals(sign))) {
////					// 需要签名
////					// 回复设备同样签名
////					Map<String, String> respParams = new TreeMap<String, String>();
////					String stamp = DateUtil.getTimestamp();
////					respParams.put("timestamp", stamp);
////					respParams.put("token", record.getToken());
////					String respSign = SignUtils.sign(respParams, SECRET);
////					result.put("url", "http://" + gwAddress + ":" + gwPort + "/auth?sign=" + respSign + "&token="
////							+ record.getToken() + "&timestamp=" + stamp);
////					// response.sendRedirect("http://" + gwAddress + ":" +
////					// gwPort + "/auth?sign=" + respSign + "&token="
////					// + record.getToken() + "&timestamp=" + stamp);
////				} else {
////					// response.sendRedirect("http://" + gwAddress + ":" +
////					// gwPort + "/auth?token=" + record.getToken());
////					result.put("url", "http://" + gwAddress + ":" + gwPort + "/auth?token=" + record.getToken());
////				}
////			} catch (Exception e) {
////				// 保存不成功
////				flag = false;
////				error = "保存失败";
////				errorCode = 1;
////			}
////		}
////
////		if (!flag) {
////			if (state == -1) {
////				// errorCode=0;
////				result.put("url", "http://www.utt.com.cn");
////				// response.sendRedirect("http://www.utt.com.cn");
////				// return;
////				// login.htm中参数错误，或者直接访问的login这个servlet，重定向到www.utt.com.cn
////			} else {
////
////			}
////			// // 登录有错误
////			// Long shopId = (long) 1;
////			// if (device != null) {
////			// shopId = device.getShop_id();
////			// }
////			// try {
////			//
////			// // 1.根据模版选择login.ftl和css及跟模版相关的图片
////			// // 2.根据wifi_cfg登录类型决定login.ftl显示的认证类型，店名
////			// // 3.根据device表中page_dir路径决定店招和logo图片
////			// // System.out.println("error ip:"+ip);
////			// // 将登录相关的访客信息传递到模版中，作为隐藏值在登录时提交
////			// Map root = new HashMap();
////			// if (error.length() > 0) {
////			// root.put("error", error);
////			// }
////			// root.put("gwaddress", gwAddress);
////			// root.put("gwport", gwPort);
////			// root.put("deviceid", deviceid);
////			// root.put("ip", ip);
////			// root.put("mac", mac);
////			// root.put("logintype", logintype);
////			// root.put("phone", phone);
////			// if ((sign != null && !"".equals(sign))) {
////			// root.put("sign", sign);
////			// }
////			// // 根据shopId查询店铺相关认证页面配置
////			// WifiConf wifiConf = memberService.getWifiConf(shopId);
////			// if (wifiConf != null) {
////			// Configuration cfg = new Configuration();
////			// cn.com.utt.vo.WifiConf conf = new cn.com.utt.vo.WifiConf();
////			// cfg.setDirectoryForTemplateLoading(new File(Config
////			// .getTemplate() + wifiConf.getTemplate_path()));
////			// // 将店铺页面配置组装成vo
////			// // WifiCofn对象传递给freemarkert模版用于生成带错误提示信息的登录页面，让用户重新登录
////			// conf.setShopId(shopId);
////			// conf.setTemplatePath(wifiConf.getTemplate_path());
////			// conf.setName(wifiConf.getName());
////			// conf.setSignPath(wifiConf.getSign_path());
////			// conf.setLogoPath(wifiConf.getLogo_path());
////			// conf.setAccessType(wifiConf.getAccess_type());
////			// conf.setSemacodePath(wifiConf.getSemacode_path());
////			// conf.setTempEnable(wifiConf.getTmp_en());
////			// if ((wifiConf.getAccess_type() & 4) == 4) {
////			// conf.setWxAccount(wifiConf.getWx_account());
////			// WxConfService wxConfService = new WxConfServiceImpl();
////			// WxConf wxConf = wxConfService.getWxConf(shopId);
////			// if (wxConf != null) {
////			// conf.setWxKeywd(wxConf.getKeyword());
////			// }
////			// }
////			// root.put("conf", conf);
////			// Template template = cfg.getTemplate("login.ftl");
////			// resp.addHeader("content-type", "text/html");
////			// resp.setCharacterEncoding("utf-8");
////			// PrintWriter out = resp.getWriter();
////			// try {
////			// template.process(root, out);
////			// } catch (TemplateException e) {
////			// logger.error("login template error!", e);
////			// } finally {
////			// out.flush();
////			// out.close();
////			// }
////			// } else {
////			// // 页面生成有问题应当提示用户
////			// logger.error("crate login page error");
////			// }
////			// } catch (BusinessException e) {
////			// logger.error("login error return!", e);
////			// // 如果查询错误怎么返回页面。
////			// // 页面生成有问题应当提示用户
////			// }
////			// }
////		}
////		result.setErrorCode(errorCode);
////		result.setErrorMsg(error);
////		return result.toJsonObject();
//		return null;
//	}
//
//	@RequestMapping(value = "/auth", method = { RequestMethod.GET })
//	public void auth(HttpServletRequest request, HttpServletResponse response) {
//
//		String deviceid = request.getParameter("deviceid");
//		String ip = request.getParameter("ip");
//		String mac = request.getParameter("mac");
//		String token = request.getParameter("token");
//		// SE2.2增加签名验证
//		String sign = request.getParameter("sign");
//		String timestamp = request.getParameter("timestamp");
//		String version = request.getParameter("v");
//
//		response.addHeader("content-type", "text/html");
//		response.setCharacterEncoding("utf-8");
//
//		PrintWriter out = null;
//		String result = "";
//		String signStr = null;
//		int state = 0;
//		AuthResult authResult = null;
//		try {
//			out = response.getWriter();
//
//			if (deviceid == null || ip == null || mac == null || token == null || deviceid.length() <= 0
//					|| ip.length() <= 0 || mac.length() <= 0 || token.length() <= 0) {
//				// key 与value之间是冒号和一个空格
//				state = 0;
//			} else {
//				if ((sign != null && !"".equals(sign))) {
//					Map<String, String> params = new TreeMap<String, String>();
//					params.put("deviceid", deviceid);
//					params.put("ip", ip);
//					params.put("mac", mac);
//					params.put("timestamp", timestamp);
//					params.put("token", token);
//					if (version != null && version.length() > 0) {
//						params.put("v", version);
//					}
//					signStr = SignUtils.sign(params, SECRET);
//				}
//				if (signStr != null && !sign.equals(signStr)) {
//					state = 0;
//				} else {
//					try {
//						authResult = jsonService.authAvailable(deviceid, mac, token);
//						if (authResult != null) {
//							state = 1;
//							if (signStr != null) {
//								result = "Auth:1;expire:" + authResult.getExpire();
//							} else {
//								// 兼容SE2.1
//								result = "Auth: 1;expire: " + authResult.getExpire();
//							}
//
//						} else {
//							state = 0;
//						}
//					} catch (BusinessException e) {
//						state = 0;
//					}
//				}
//			}
//			// 加上时间戳和签名
//			if (signStr != null || "1.2".equals(version)) {
//				// SE2.2
//				if (state == 0) {
//					result = "Auth:0";
//				}
//				String stamp = DateUtil.getTimestamp();
//				JSONObject jsonObject = new JSONObject();
//				jsonObject.put("timestamp", stamp);
//				if (state == 0) {
//					jsonObject.put("state", "0");
//				} else {
//					if (authResult.getExpire() > 0) {
//						jsonObject.put("state", "1");
//					} else {
//						jsonObject.put("state", "0");
//					}
//					jsonObject.put("expire", authResult.getExpire() + "");
//					if (version != null && version.length() > 0) {
//						// 需要返回下行速率
//						jsonObject.put("rxrate", authResult.getRxrate() + "");
//						jsonObject.put("txrate", authResult.getTxrate() + "");
//					}
//				}
//				out.print(jsonObject);
//			} else {
//				// 兼容SE2.1
//				if (state == 0) {
//					result = "Auth: 0";
//				}
//				out.print(result);
//			}
//
//			out.flush();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (out != null) {
//				out.close();
//			}
//		}
//	}
//
//	@RequestMapping(value = "/macValidate", method = { RequestMethod.GET })
//	public void macValidate(HttpServletRequest request, HttpServletResponse response) {
//
//		String deviceid = request.getParameter("deviceid");
//		String ip = request.getParameter("ip");
//		String mac = request.getParameter("mac");
//		String sign = request.getParameter("sign");
//		String timestamp = request.getParameter("timestamp");
//		long stamp = System.currentTimeMillis();
//		String version = request.getParameter("v");
//		// 参数有为空的怎么处理？
//		// 如果deviceid等参数为空，不能登录。
//		// 如果根据deviceid查询不到店铺说明还没有绑定过，使用UTT默认店铺表
//		response.addHeader("content-type", "text/html");
//		response.setCharacterEncoding("utf-8");
//		JSONObject jsonObject = new JSONObject();
//		PrintWriter out = null;
//		try {
//			out = response.getWriter();
//
//			if (deviceid == null || ip == null || mac == null || deviceid.length() <= 0 || ip.length() <= 0
//					|| mac.length() <= 0 || timestamp == null || timestamp.length() <= 0) {
//				jsonObject.put("state", "0");
//				jsonObject.put("timestamp", stamp);
//				jsonObject.put("error", "param is null");
//				out.print(jsonObject);
//			} else {
//				String signStr = null;
//				if ((sign != null && !"".equals(sign))) {
//					Map<String, String> params = new TreeMap<String, String>();
//					params.put("deviceid", deviceid);
//					params.put("ip", ip);
//					params.put("mac", mac);
//					params.put("timestamp", timestamp);
//					if (version != null && version.length() > 0) {
//						params.put("v", version);
//					}
//					signStr = SignUtils.sign(params, SECRET);
//				}
//				if (signStr != null && sign.equals(signStr) || sign == null) {
//					Device device = deviceService.queryDeviceBySn(deviceid);
////					User user = userService.queryById(device.getUserId());
////					if (device != null && device.getUserId() != null) {
////						// mac查询黑白灰名单
////						// 先判断是否有还未过期的登录记录，如果有则无感知认证
////						UnExpiredRecord unExpiredRecord = userRecordService.queryUnExpiredRecord(device.getSn(),
////								user.getCfgId(), ip, mac);
////						if (unExpiredRecord != null && unExpiredRecord.getExpire() > 0) {
////							jsonObject.put("expire", unExpiredRecord.getExpire() + "");
////							jsonObject.put("state", "1");
////							jsonObject.put("authtype", "3");
////							jsonObject.put("timestamp", stamp);
////							// KB/s convert to Kb/s
////							jsonObject.put("rxrate", (unExpiredRecord.getRxrate() * 8) + "");
////							jsonObject.put("txrate", (unExpiredRecord.getTxrate() * 8) + "");
////							jsonObject.put("token", unExpiredRecord.getToken());
////							out.print(jsonObject);
////						} else {
////							// mac地址不在
////							jsonObject.put("state", "0");
////							jsonObject.put("timestamp", stamp);
////							jsonObject.put("error", "mac not exist");
////							out.print(jsonObject);
////						}
////					} else {
////						// 设备不存在
////						jsonObject.put("state", "0");
////						jsonObject.put("timestamp", stamp);
////						jsonObject.put("error", "device not register yet");
////						out.print(jsonObject);
////					}
//				} else {
//					// 签名不正确
//					jsonObject.put("state", "0");
//					jsonObject.put("timestamp", stamp);
//					jsonObject.put("error", "invalid sign");
//					out.print(jsonObject);
//				}
//			}
//
//			out.flush();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (out != null) {
//				out.close();
//			}
//		}
//	}
//	
//	@RequestMapping(value = "/ping", method = { RequestMethod.GET })
//	public void ping(HttpServletRequest request, HttpServletResponse response) {
//
//		response.addHeader("content-type", "text/html");
//		response.setCharacterEncoding("utf-8");
//		PrintWriter out = null;
//		try {
//			out = response.getWriter();
//			StringBuffer reponse = new StringBuffer();
//			String result = reponse.toString();
//			out.print("Pong;" + result);
//			out.flush();
//		} catch (Exception e) {
//			e.printStackTrace();
//		} finally {
//			if (out != null) {
//				out.close();
//			}
//		}
//	}

}